// packageRecruit/pages/work-data/work-data.js
import uCharts from '../../../utils/u-charts'
var uChartsInstance = {};
import dayjs from 'dayjs'
import user from '../../../utils/user'
import {
    signUpList,
    operatingTopData,
    operatingChartData
} from '../../api/recruit'
import { getInsuranceProgramme } from "../../../api/app"
import { dateFormat } from "../../../utils/util"
Page({

    /**
     * 页面的初始数据
     */
    data: {
        date: '2022-02',
        cWidth: 750,
        cHeight: 500,
        pixelRatio: 2,
        hasNextPage:false,//是否下一页
        signList:[],
        totalCount:0, //操作计数
        topInfo:{},//头部信息,
        pageNum:1,
        pageSize:20,
        chartType:"WEEK",
        applyState:[],//接单状态字典内容
        signInState:[],//签到状态字典内容
    },

    onLoad(options) {
        
    },
    // 头部数据
    getOperatingTopData(){
        operatingTopData().then(res=>{
            console.log(res,'res头部数据')
            res.totalApplyCountClone =  Math.abs(res.totalApplyCount)
            res.applyCountChangeClone = Math.abs(res.applyCountChange)
            res.shareChangeClone = Math.abs(res.shareChange)
            this.setData({
                topInfo:res
            })
        })
    },
    // 切换本周 上周
    onEditChartData(event){
        console.log(event.currentTarget.dataset)
        const { type } = event.currentTarget.dataset
        this.setData({
            chartType:type
        })
        this.getServerData()

    },

    onReady() {
        //这里的第一个 750 对应 css .charts 的 width
        const cWidth = 750 / 750 * wx.getSystemInfoSync().windowWidth - 50;
        //这里的 500 对应 css .charts 的 height
        const cHeight = 500 / 750 * wx.getSystemInfoSync().windowWidth;
        const pixelRatio = wx.getSystemInfoSync().pixelRatio;
        this.setData({
            cWidth,
            cHeight,
            pixelRatio
        });
        this.getServerData()
        this.getOperatingTopData()
    },
    onShow() {
        this.setData({
            pageNum:1,
            signList:[],
            date:dateFormat('YYYY-mm',new Date())
        })
        user.waitLogin().then(()=>{
            this.getSignUpList()
            this.getInsuranceProgramme()
            this.getSignInState()
        })
    },
    // 接单字典查询
    getInsuranceProgramme(){
        getInsuranceProgramme({
            dictType: 'zp_apply_state'
        }).then(res=>{
            this.setData({
                applyState:res
            })
        })
    },
    // 签到字典查询
    getSignInState(){
        getInsuranceProgramme({
            dictType: 'zp_sign_in_state'
        }).then(res=>{
            console.log(res)
            this.setData({
                signInState:res
            })
        }) 
    },
    // 到达底部事件
    threshold(){
        if(!this.data.hasNextPage){
            return
        }
        this.setData({
            pageNum:this.data.pageNum += 1
        })
        this.getSignUpList()
    },
    // 切换日期关列表
    bindDateChange(event){
        console.log(event.detail.value,'event')
        this.setData({
            date:event.detail.value,
            pageNum:1,
            signList:[]
        })
        this.getSignUpList()
    },
    async getSignUpList(){
        // 获取历史报名列表
        const result = await signUpList({
            queryMonth:this.data.date,
            pageNum:this.data.pageNum,
            pageSize:this.data.pageSize
        })
        if(!result.hasNextPage){
            this.setData({
                hasNextPage:result.hasNextPage
            })
        }else{
            this.setData({
                hasNextPage:result.hasNextPage
            })
        }
        let arr = []
        arr.push(...this.data.signList)
        arr.push(...result.list)
        arr.forEach((item,index)=>{
            arr[index].createTime = item.createTime.split(' ')[0]
        })
        
        this.setData({
            signList:arr,
            totalCount:result.totalCount
        })
        console.log(result,'result')
    },
    getServerData() {
        //模拟从服务器获取数据时的延时
        operatingChartData({
            queryRange:this.data.chartType
        }).then(res=>{
            const chartData = {
                categories: [],
                series: [{
                    name: "报名",
                    data: []
                }, {
                    name: "浏览",
                    data: []
                }]
			};
			console.log(55555, res);
            //  Object.keys(res)方法拿到的键名是乱序 需要先排序 然后在使用循环
            let tempArr = Object.keys(res).sort((a,b)=>{
                return a > b ? 1 : -1
			})
			let tempArr2 = tempArr.map(i => dayjs(i).format('MM-DD'))
            chartData.categories = tempArr2
            console.log(tempArr,'tempArr')
            console.log(tempArr2,'tempArr2')
            tempArr.forEach((key) => {
                chartData.series[0].data.push(res[key].applyCount)
                chartData.series[1].data.push(res[key].viewsCount)
                console.log(res[key],key,'新key') // foo
            })
            this.drawCharts('afMCYQMEmXXVAjNQFJvvfxbLSHuxNEOL', chartData);
        })
    },

    drawCharts(id, data) {
        const query = wx.createSelectorQuery().in(this);
        query.select('#' + id).fields({
            node: true,
            size: true
        }).exec(res => {
            if (res[0]) {
                const canvas = res[0].node;
                const ctx = canvas.getContext('2d');
                canvas.width = res[0].width * this.data.pixelRatio;
                canvas.height = res[0].height * this.data.pixelRatio;
                uChartsInstance[id] = new uCharts({
                    animation: true,
                    background: "#FFFFFF",
                    canvas2d: true,
                    categories: data.categories,
                    color: ["#00D679", "#DEE0E3"],
                    context: ctx,
                    extra: {
                        line: {
                            type: 'curve',
                            width: 3,
                            disabled: false,
                          },
                          column: {
                            type: "group",
                            width: 30,
                            activeBgColor: "#000000",
                            activeBgOpacity: 0.08
                        },
                        area: { // type必须设置成 area
                            type: "curve", // 曲线图
                            opacity: 0.8, // 透明度
                            addLine: true, 
                            width: 3, // 线粗多少
                            gradient: true
                        },
                        tooltip:{
                            showBox: true,
                            showCategory: true
                        },
                    },

                    dataLabel: false,
                    candle: {
                        dataLabel: false,
                    },
                    height: this.data.cHeight * this.data.pixelRatio,
                    legend: {
                        show:false,
                    },
                    padding: [15, 15, 0, 5],
                    pixelRatio: this.data.pixelRatio,
                    series: data.series,
                    type: "area",
                    width: this.data.cWidth * this.data.pixelRatio,
                    xAxis: {
                        // disabled: true,
						disableGrid: true,
						labelCount: 2,
						rotateLabel: true,
						fontColor: '#9497b1'
						// fontSize: 
                    },
                    yAxis: {
                        disabled: true,
						gridType:"dash",
						dashLength: '2',
						gridColor: '#DEE0E3',
                        data: [{
                            min: 0
                        }]
                    }
                });
            } else {
                console.error("[uCharts]: 未获取到 context");
            }
        });
    },
    tap(e) {
        uChartsInstance[e.target.id].touchLegend(e);
        uChartsInstance[e.target.id].showToolTip(e);
    }
})